from contextlib import contextmanager

from config.secure import SQLALCHEMY_DATABASE_URI
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base


class MysqlDBConnection(object):

    def __init__(self):
        self.engine = create_engine(SQLALCHEMY_DATABASE_URI, pool_recycle=600)
        self.Base = declarative_base()
        self.DBSession = sessionmaker(bind=self.engine)
        self.session = self.DBSession()

    @contextmanager
    def auto_commit(self):
        try:
            yield
            self.session.commit()
        except Exception as e:
            self.session.rollback()
            raise e

db = MysqlDBConnection()

